package com.yyn.server.dao;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;

@Service
public class ServerDao {
    //存连接上的 用户Channel  指定发送消息
    Map<String, SocketChannel> socketChannelMap = new HashMap<>();
//    查看该信息发了给谁
Map<String, SocketChannel> toUsers = new HashMap<>();


    public void server() throws Exception {
//        创服务端channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//        绑定端口
        serverSocketChannel.bind(new InetSocketAddress(9003));
//        非阻塞
        serverSocketChannel.configureBlocking(false);
//        创selector
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            int select = selector.select();//轮询
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                SelectionKey key = iterator.next();//轮询出的每个key
                String message = null;
                if (key.isAcceptable()) {//连接操作
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();//进行连接
//                    每次连接都保存它的地址和通道
                    socketChannelMap.put(socketChannel.getLocalAddress().toString(), socketChannel);
                    System.out.println(socketChannel.getLocalAddress().toString() + "连接上了selector");
                    System.out.println("服务端待连接");
                    socketChannel.write(ByteBuffer.wrap("服务器发来的 连接成功".getBytes()));
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);//会被轮询 读
                } else if (key.isReadable()) {//客户端写入数据     服务端读
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    SocketChannel channel = (SocketChannel) key.channel();
                    int len = 0;
                    while ((len = channel.read(buffer)) > 0) {//如果消息发送完毕  = -1
                        buffer.flip();
                        Set<SelectionKey> selectionKeys1 = selector.selectedKeys();
                        message = new String(buffer.array(), 0, len);
                        System.out.println("服务端收到消息" + message + "     ip:" + channel.getLocalAddress().toString());
//
//                    广播给客户端
                        send(message, key);
//                        继续让它对读感兴趣
                        channel.register(selector, SelectionKey.OP_READ);
                    }
                    channel.register(selector, SelectionKey.OP_WRITE);
                } else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.put((channel.getLocalAddress() + "发的信息：" + message).getBytes());
                    buffer.flip();
                    channel.write(buffer);
                }
                iterator.remove();

            }
        }
    }
    public void send(String message,SelectionKey key) throws IOException {
        Selector selector = key.selector();
        Set<SelectionKey> selectionKeys = selector.keys();
        for (SelectionKey selectionKey : selectionKeys) {
            SelectableChannel channel = selectionKey.channel();
            if( channel instanceof SocketChannel && channel != key.channel() ) {//判断
                System.out.println("要发送给："+((SocketChannel) channel).getLocalAddress()+"===="+message);
                ((SocketChannel) channel).write(ByteBuffer.wrap(message.getBytes()));
//                toUsers.put(String.valueOf(UUID.randomUUID()), SocketChannel.open(((SocketChannel) channel).getLocalAddress()));
            }

        }


        }
    }

